package dao

import (
	"Im/global"
	"context"
	"go.mongodb.org/mongo-driver/bson"
	"log"
)

func FindOne(name string, model any, data any) error {
	err := global.DB.Collection(name).FindOne(context.Background(), model).Decode(data)
	if err != nil {
		return err
	}
	return nil
}

func InsertOne(name string, model any) error {
	_, err := global.DB.Collection(name).InsertOne(context.Background(), model)
	return err
}

// 查找多个用户的方法
func Find(name string, model any, data any) (any, error) {
	//建立查询
	filed, err := global.DB.Collection(name).Find(context.Background(), model)
	if err != nil {
		log.Println(err.Error())
	}
	//存储查询的结果
	urs := make([]any, 0)
	//遍历查询的结果
	for filed.Next(context.Background()) {
		//解码绑定的数据
		err = filed.Decode(&data)
		if err != nil {
			log.Println(err)
			return nil, err
		}
		//将解析到的数据添加到数组中
		urs = append(urs, data)
	}
	return urs, err
}

// 更新单个数据的方法
func UpdateOne(name string, model any, data any) error {
	data = bson.M{
		"$set": data,
	}
	_, err := global.DB.Collection(name).UpdateOne(context.Background(), model, data)
	return err

}

func UpdateArrOne(name string, model any, data any) error {
	data = bson.M{
		"$push": data,
	}
	_, err := global.DB.Collection(name).UpdateOne(context.Background(), model, data)
	return err
}
func DeleteArrOne(name string, model any, data any) error {
	data = bson.M{
		"$pull": data,
	}
	_, err := global.DB.Collection(name).UpdateOne(context.Background(), model, data)
	return err
}
